﻿using Entity;
using Microsoft.AspNetCore.Http;
using ServiceCore;
using ServiceCore.Tool.NPOI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using System.Web;
using ServiceCore.Tool;
using System.ComponentModel;

namespace Customer.Bussiness_Service
{
    public interface Icard_service
    {
        /// <summary>
        /// 卡加密
        /// </summary>
        /// <param name="card_no"></param>
        /// <returns></returns>
        ResultObjModel encryption_card(string card_no);
        /// <summary>
        /// 保存卡信息
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel save_card(save_card_params Params);
        /// <summary>
        /// 编辑卡信息
        /// </summary>
        /// <param name="card_id">卡ID</param>
        /// <param name="card_no">卡编号</param>
        /// <param name="card_pwd">卡密码</param>
        /// <param name="rk_baseuserid">分配商户</param>
        /// <returns></returns>
        ResultObjModel edit_card(string card_id, string rk_baseuserid);//string card_no, string card_pwd,
        /// <summary>
        /// 获取卡信息列表
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultListModel<get_card_pagelist_item> get_card_pagelist(get_card_pagelist_params Params);
        /// <summary>
        /// 删除单卡信息
        /// </summary>
        /// <param name="card_ids"></param>
        /// <returns></returns>
        ResultObjModel del_card(string[] card_ids);
        /// <summary>
        /// 批量修改商户
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel batch_set_baseuserid(bacth_set_baseuserid_params Params);
        /// <summary>
        /// 下载列表
        /// </summary>
        /// <param name="query"></param>
        void rk_card_down(get_card_pagelist_params query);

        /// <summary>
        ///  充值管理 卡列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<card_list_Item> get_card_list_for_shop(card_search query);
        /// <summary>
        ///   充值管理导出excel
        /// </summary>
        /// <param name="query"></param>
        void rk_card_down_for_shop(card_search query);
        /// <summary>
        /// 开卡激活
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel start_activation_card(activation_Params Params);
        /// <summary>
        ///  后台充值
        /// </summary>
        /// <param name="card_id"></param>
        /// <param name="recharge_money"></param>
        /// <returns></returns>
        ResultObjModel start_recharge(string card_id, decimal? recharge_money);
        /// <summary>
        /// 保存卡信息
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel edit_card(edit_card_Params Params);
        /// <summary>
        /// 批量修改卡状态
        /// </summary>
        /// <param name="Parmas"></param>
        /// <returns></returns>
        ResultObjModel batch_change_state(batch_change_params Parmas, bool is_crm = false);

        /// <summary>
        /// 卡消费记录列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<card_record_Item> card_record_pagelist(card_record_search query);
        /// <summary>
        /// 卡消费记录列表下载
        /// </summary>
        /// <param name="query"></param>
        void rk_cardrecord_down_for_shop(card_record_search query);

        /// <summary>
        /// 获取卡信息
        /// </summary>
        /// <param name="baseuserid"></param>
        /// <param name="card_no"></param>
        /// <returns></returns>
        ResultObjModel get_card(string baseuserid, string card_no);
    }
    public class card_service : Icard_service
    {
        private readonly IToole_DI _tool;
        private readonly INpoi_service _excelservice;
        private readonly IHttpContextAccessor _context;

        public card_service(IToole_DI Tool, INpoi_service Excelservice, IHttpContextAccessor Context)
        {
            _tool = Tool;
            _excelservice = Excelservice;
            _context = Context;
        }
        /// <summary>
        /// 卡加密操作
        /// </summary>
        /// <returns></returns>
        public ResultObjModel encryption_card(string card_no)
        {
            return CoreStartDo.ResultAction(result =>
            {
                string set_pwd = SecurityToMd5.Start($"R{card_no}K_^0^"); 
                result.code = 0;
                result.data = set_pwd;
                result.msg = "success";
                return result;
            });
        } 
        /// <summary>
        /// 保存卡信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel save_card(save_card_params Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.rk_baseuserid))
                {
                    result.code = 1;
                    result.msg = "请选择用卡商户";
                    return result;
                }
                if (Params.card_nos == null || !Params.card_nos.Any() || Params.card_nos.Where(s => string.IsNullOrWhiteSpace(s.card_no)).Any())
                {
                    result.code = 1;
                    result.msg = "存在空卡号";
                    return result;
                }
                if (Params.card_nos.Where(s => s.card_no.Length > 10).Any())
                {
                    result.code = 1;
                    result.msg = $"{string.Join(',', Params.card_nos.Where(s => s.card_no.Length > 10).Select(s => s.card_no).ToArray())}位数不合法";
                    return result;
                }
                if (Params.card_nos.Where(s => string.IsNullOrWhiteSpace(s.card_pwd)).Any())
                {
                    result.code = 1;
                    result.msg = "存在未设置卡密码的数据,无法提交";
                    return result;
                }
                var no_auth_list = Params.card_nos.Where(s => s.card_pwd != SecurityToMd5.Start($"R{s.card_no}K_^0^")).ToList();
                if (no_auth_list.Count > 0)
                {
                    result.code = 1;
                    result.msg = $"存在非法的密码提交:{string.Join(",", no_auth_list.Select(s => s.card_no).ToArray())}";
                    return result;
                }
                //验证卡号是否存在
                string[] have_card = _tool.di_db.Get_rk_List<string>("select card_no from rk_card where card_no in @card_nos", new { card_nos = Params.card_nos.Select(s => s.card_no) }).ToArray();
                if (have_card.Any())
                {
                    result.code = 1;
                    result.msg = $"{string.Join(",", have_card)}卡号已经存在";
                    return result;
                }
                //创造数据准备开卡
                List<rk_card> new_card_list = new List<rk_card>();
                foreach (var item in Params.card_nos)
                {
                    new_card_list.Add(new rk_card()
                    {
                        card_id = $"{Params.rk_baseuserid}-{item.card_no}",
                        addtime = DateTime.Now,
                        now_balance = 0,
                        card_no = item.card_no,
                        card_pwd = item.card_pwd,
                        card_state = card_state.未激活,
                        original_balance = 0,
                        rk_baseuserid = Params.rk_baseuserid,
                        add_crm_uid = _tool.di_user.USER == null ? "" : _tool.di_user.USER.uid
                    });
                }
                int add_item = _tool.di_db.do_rk_Execute(_tool.di_db.AddBySqlStr<rk_card>(), new_card_list);
                if (add_item > 0)
                {
                    result.code = 0;
                    result.data = "开卡成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "开卡失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 编辑卡
        /// </summary>
        /// <returns></returns>
        public ResultObjModel edit_card(string card_id, string rk_baseuserid) //string card_no, string card_pwd,
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(card_id))
                {
                    result.code = 1;
                    result.msg = "卡ID未知,修改失败";
                    return result;
                }
                //if (string.IsNullOrWhiteSpace(card_no))
                //{
                //    result.code = 1;
                //    result.msg = "卡号未知,修改失败";
                //    return result;
                //}
                //if (string.IsNullOrWhiteSpace(card_pwd))
                //{
                //    result.code = 1;
                //    result.msg = "设置卡密码未知,修改失败";
                //    return result;
                //}
                //if (card_pwd != SecurityToMd5.Start($"R{card_no}K_^0^"))
                //{
                //    result.code = 1;
                //    result.msg = "提交密码不合法";
                //    return result;
                //}
                if (string.IsNullOrWhiteSpace(rk_baseuserid))
                {
                    result.code = 1;
                    result.msg = "未设置用户,修改失败";
                    return result;
                }
                ////验证卡号是否存在
                //var have_card = _tool.di_db.Get_rk_List<int>("select count(*) from rk_card where card_no=@card_no and card_id<>@card_id", new { card_no, card_id }).FirstOrDefault();
                //if (have_card > 0)
                //{
                //    result.code = 1;
                //    result.msg = "卡号已经存在,修改失败";
                //    return result;
                //}
                var update_card = _tool.di_db.Get_rk_List<rk_card>("select top 1 * from rk_card where card_id=@card_id", new { card_id }).FirstOrDefault();
                if (update_card == null)
                {
                    result.code = 1;
                    result.msg = "待修改卡不存在";
                    return result;
                }
                //int update = _tool.di_db.do_rk_Execute("update rk_card set card_id=@newcard_id,card_no=@card_no,card_pwd=@card_pwd,rk_baseuserid=@rk_baseuserid where card_id=@oldcard_id", new
                //{
                //    card_no,
                //    card_pwd,
                //    rk_baseuserid,
                //    newcard_id = $"{rk_baseuserid}-{card_no}",
                //    oldcard_id = card_id
                //});
                int update = _tool.di_db.do_rk_Execute("update rk_card set rk_baseuserid=@rk_baseuserid where card_id=@card_id", new
                {
                    rk_baseuserid,
                    card_id
                });
                if (update > 0)
                {
                    result.code = 0;
                    result.msg = "修改成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "修改失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 获取卡列表信息
        /// </summary>
        /// <returns></returns>
        public ResultListModel<get_card_pagelist_item> get_card_pagelist(get_card_pagelist_params Params)
        {
            return CoreStartDo.ResultAction<ResultListModel<get_card_pagelist_item>>(result =>
            {
                string sql = "select a.card_id,b.UserName as rk_login_name,a.card_no,a.addtime,a.card_state from rk_card a left join [user] b on a.rk_baseuserid=b.Id";
                string where = " where 1=1";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (!string.IsNullOrWhiteSpace(Params.card_no))
                {
                    where += " and a.card_no=@card_no";
                    query_dy.card_no = Params.card_no;
                }
                if (!string.IsNullOrWhiteSpace(Params.rk_login_name))
                {
                    where += " and b.UserName=@rk_login_name";
                    query_dy.rk_login_name = Params.rk_login_name;
                }
                if (!string.IsNullOrWhiteSpace(Params.rk_baseuserid))
                {
                    where += " and a.rk_baseuserid=@rk_baseuserid";
                    query_dy.rk_baseuserid = Params.rk_baseuserid;
                }
                var result_list = _tool.di_db.GetRKPageList<get_card_pagelist_item>(sql, where, "a.addtime", query_dy, Params.IsPage, Params.page, Params.pagesize);
                return result_list;
            });
        }
        /// <summary>
        /// 删除单/多卡
        /// </summary>
        /// <returns></returns>
        public ResultObjModel del_card(string[] card_ids)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (card_ids == null || !card_ids.Any())
                {
                    result.code = 1;
                    result.msg = "卡ID未入参";
                    return result;
                }
                var del_card = _tool.di_db.Get_rk_List<rk_card>("select top 1 * from rk_card where card_id in @card_ids", new { card_ids });
                if (del_card == null)
                {
                    result.code = 1;
                    result.msg = "待删除卡不存在";
                    return result;
                }
                //准备一个事务
                string error = "";
                int tran_rows = _tool.di_db.StartRKTran((conn, tran) =>
                {
                    int rows = 0;
                    //rows += conn.Execute("delete from rk_card where card_id in @card_ids", new { card_ids }, tran);
                    //rows += conn.Execute("delete from rk_card_record where card_id in @card_ids", new { card_ids }, tran);
                    return rows;
                }, ref error);
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "删除成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "删除失败:" + error;
                }
                return result;
            });
        }
        /// <summary>
        ///  批量修改商户
        /// </summary>
        /// <returns></returns>
        public ResultObjModel batch_set_baseuserid(bacth_set_baseuserid_params Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.rk_baseuserid))
                {
                    result.code = 1;
                    result.msg = "分配商户不能为空";
                    return result;
                }
                if (!Params.card_ids.Any() || Params.card_ids == null)
                {
                    result.code = 1;
                    result.msg = "未选择任何卡";
                    return result;
                }
                int update_set = _tool.di_db.do_rk_Execute("update rk_card set rk_baseuserid=@rk_baseuserid,card_id=@rk_baseuserid+'-'+card_no where card_id in @card_ids", new {  Params.rk_baseuserid,  Params.card_ids });
                if (update_set > 0)
                {
                    result.code = 0;
                    result.msg = "修改成功";
                    result.data = update_set;
                }
                else
                {
                    result.code = 1;
                    result.msg = "修改失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 导出卡信息
        /// </summary>
        public void rk_card_down(get_card_pagelist_params query)
        {
            query.IsPage = false;
            var listresult = get_card_pagelist(query);
            string title = $"{DateTime.Now.ToString("yyyy-MM-dd")}_卡信息.xlsx";
            _excelservice.ExcelExportService(title, listresult.rows, dosomething: fs =>
            {
                _context.HttpContext.Response.ContentType = "application/octet-stream;charset=UTF-8";
                _context.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(title, System.Text.Encoding.UTF8));
                int bufferSize = Convert.ToInt32(fs.Length);
                byte[] buffer;
                buffer = new byte[bufferSize];
                int currentRead = fs.Read(buffer, 0, bufferSize);
                _context.HttpContext.Response.Body.Write(buffer, 0, currentRead);
                _context.HttpContext.Response.Body.Flush();
            });
        }
        #region 充值管理
        public ResultListModel<card_list_Item> get_card_list_for_shop(card_search query)
        {

            return CoreStartDo.ResultAction<ResultListModel<card_list_Item>>(result =>
            {
                string sql = "select * from rk_card";
                string where = " where 1=1 and rk_baseuserid=@rk_baseuserid";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.rk_baseuserid = _tool.di_user.RK_USER.BaseUserId;
                if (!string.IsNullOrWhiteSpace(query.card_no))
                {
                    where += " and card_no=@card_no";
                    query_dy.card_no = query.card_no;
                }
                if (query.state.HasValue)
                {
                    where += " and card_state=@card_state";
                    query_dy.card_state = query.state.Value;
                }
                //else
                //{
                //    where += " and card_state>=@card_state";
                //    query_dy.card_state = card_state.已激活;//显示已激活和已禁用两种状态的卡
                //}
                if (query.min_balance.HasValue)
                {
                    where += " and now_balance>=@min_balance";
                    query_dy.min_balance = query.min_balance.Value;
                } 
                if (query.max_balance.HasValue)
                {
                    where += " and now_balance<=@max_balance";
                    query_dy.max_balance = query.max_balance.Value;
                }
                if (!string.IsNullOrWhiteSpace(query.activation_time_sdt))
                {
                    where += " and activation_time>=@activation_time_sdt";
                    query_dy.activation_time_sdt = query.activation_time_sdt;
                }
                if (!string.IsNullOrWhiteSpace(query.activation_time_edt))
                {
                    where += " and activation_time<=@activation_time_edt";
                    query_dy.activation_time_edt = query.activation_time_edt;
                }
                if (!string.IsNullOrWhiteSpace(query.expiration_time_sdt))
                {
                    where += " and expiration_time>=@expiration_time_sdt";
                    query_dy.expiration_time_sdt = query.expiration_time_sdt;
                }
                if (!string.IsNullOrWhiteSpace(query.expiration_time_edt))
                {
                    where += " and expiration_time<=@expiration_time_edt";
                    query_dy.expiration_time_edt = query.expiration_time_edt;
                } 
                if (!string.IsNullOrWhiteSpace(query.remark_a))
                {
                    where += " and remark_a like @remark_a";
                    query_dy.remark_a = $"%{ query.remark_a}%";
                }
                ResultListModel<card_list_Item> result_list = _tool.di_db.GetRKPageList<card_list_Item>(sql, where, "addtime", query_dy, query.IsPage, query.page, query.pagesize);
                //开个线程检测一下 如果有过期的东西 直接更新到已过期
                if (result_list.rows.Where(s => s.expiration_time <= DateTime.Now).Any())
                {
                    Task.Factory.StartNew(() =>
                    {
                        var card_ids = result_list.rows.Where(s => s.expiration_time <= DateTime.Now && s.card_state != card_state.已过期).Select(s => s.card_id);
                        _tool.di_db.do_rk_Execute("update rk_card set card_state=@card_state where card_id  in card_ids", new { card_state = card_state.已过期, card_ids = card_ids });
                    });
                }
                return result_list;
            });
        } 
        /// <summary>
        /// 导出卡信息
        /// </summary>
        public void rk_card_down_for_shop(card_search query)
        {
            query.IsPage = false;
            var listresult = get_card_list_for_shop(query);
            string title = $"{DateTime.Now.ToString("yyyy-MM-dd")}_卡信息.xlsx";
            _excelservice.ExcelExportService(title, listresult.rows, dosomething: fs =>
            {
                _context.HttpContext.Response.ContentType = "application/octet-stream;charset=UTF-8";
                _context.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(title, System.Text.Encoding.UTF8));
                int bufferSize = Convert.ToInt32(fs.Length);
                byte[] buffer;
                buffer = new byte[bufferSize];
                int currentRead = fs.Read(buffer, 0, bufferSize);
                _context.HttpContext.Response.Body.Write(buffer, 0, currentRead);
                _context.HttpContext.Response.Body.Flush();
            });
        }

        /// <summary>
        /// 开卡激活
        /// </summary>
        public ResultObjModel start_activation_card(activation_Params Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.card_no))
                {
                    result.code = 1;
                    result.msg = "卡号不能为空";
                    return result;
                }
                if (!Params.original_balance.HasValue)
                {
                    Params.original_balance = 0;
                }
                if (!Params.expiration_time.HasValue)
                {
                    result.code = 1;
                    result.msg = "有效截至日期不能为空";
                    return result;
                }
                if (!Params.card_state.HasValue)
                {
                    result.code = 1;
                    result.msg = "卡状态不能为空";
                    return result;
                }
                //验证卡有效性
                rk_card card_Item = _tool.di_db.Get_rk_List<rk_card>("select top 1 * from rk_card where card_no=@card_no", new { card_no = Params.card_no }).FirstOrDefault();
                if (card_Item == null)
                {
                    result.code = 1;
                    result.msg = "非法的充值卡,无法激活";
                    return result;
                }
                if (card_Item.card_state != card_state.未激活)
                {
                    result.code = 1;
                    result.msg = "当前卡已被激活,无法重复激活";
                    return result;
                }
                if (card_Item.rk_baseuserid != _tool.di_user.RK_USER.BaseUserId)
                {
                    result.code = 1;
                    result.msg = "当前卡不属于您,无法激活";
                    return result;
                }
                User u_mod = _tool.di_db.Get_rk_List<User>("select top 1 * from [user] where Id=@Id", new { Id = _tool.di_user.RK_USER.Id }).FirstOrDefault();
                if (u_mod == null)
                {
                    result.code = 1;
                    result.msg = "小朋友,你是否有许多问号";
                    return result;
                }
                //组装数据 
                string update_sql = _tool.di_db.UpdateBySqlstr<rk_card>(new string[] { "card_state", "expiration_time", "card_alias", "activation_time", "remark_a", "remark_b", "original_balance", "now_balance" }, new string[] { "card_id=@card_id" });
                card_Item.card_state = Params.card_state.Value;
                card_Item.original_balance = Params.original_balance.Value;
                card_Item.remark_a = Params.remark_a;
                card_Item.remark_b = Params.remark_b;
                card_Item.card_alias = Params.card_alias;
                card_Item.expiration_time = Params.expiration_time;
                card_Item.activation_time = DateTime.Now;
                card_Item.now_balance = Params.original_balance.Value;
                rk_card_record org_card_list = new rk_card_record()
                {
                    addtime = DateTime.Now,
                    card_id = card_Item.card_id,
                    card_no = card_Item.card_no,
                    card_record_id = _tool.di_getid.IGet_SnowFlake_Id,
                    in_price = card_Item.original_balance,
                    out_price = 0,
                    operation_remark = "开卡激活",
                    pay_details = $"开卡激活,初始金额入账{card_Item.now_balance}元",
                    before_price = 0,
                    order_no = "activation_" + _tool.di_getid.IGet_SnowFlake_Id,
                    operation_subject = u_mod.Name,
                    operation_subject_key = u_mod.Id,
                    record_type = record_type.开卡,
                    rk_baseuserid = _tool.di_user.RK_USER.BaseUserId,
                    is_mch = false
                };
                string error = "";
                int tran_rows = _tool.di_db.StartRKTran((conn, tran) =>
                {
                    int rows = 0;
                    rows += conn.Execute(update_sql, card_Item, tran);
                    rows += conn.Execute(_tool.di_db.AddBySqlStr<rk_card_record>(), org_card_list, tran);
                    return rows;
                }, ref error);
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "开卡激活成功";
                    result.data = tran_rows;
                }
                else
                {
                    result.code = 1;
                    result.msg = "开卡激活失败:" + error;
                    result.data = tran_rows;
                }
                return result;
            });
        } 
        /// <summary>
        /// 开始充值
        /// </summary>
        /// <returns></returns>
        public ResultObjModel start_recharge(string card_id,decimal? recharge_money) {
            return CoreStartDo.ResultAction(result=> {
                if (string.IsNullOrWhiteSpace(card_id))
                {
                    result.code = 1;
                    result.msg = "卡号不能为空";
                    return result;
                }
                if (!recharge_money.HasValue)
                {
                    result.code = 1;
                    result.msg = "请指定充值金额";
                    return result;
                }
                if (recharge_money.Value == 0)
                {
                    result.code = 1;
                    result.msg = "充值金额不得为0";
                    return result;
                }
                if (recharge_money.Value < 0)
                {
                    result.code = 1;
                    result.msg = "你想抓龙吗？";
                    return result;
                }
                var card_Item = _tool.di_db.Get_rk_List<rk_card>("select top 1 * from rk_card where card_id=@card_id", new { card_id }).FirstOrDefault();
                if(card_Item == null)
                {
                    result.code = 1;
                    result.msg = "充值卡不存在";
                    return result;
                }
                if (card_Item.card_state != card_state.已激活)
                {
                    result.code = 1;
                    result.msg = $"当前卡{card_Item.card_state.ToString()}无法进行充值操作";
                    return result;
                }
                if (card_Item.expiration_time.HasValue && card_Item.expiration_time <= DateTime.Now)
                {
                    result.code = 1;
                    result.msg = "当前卡已过期,无法进行充值操作";
                    return result;
                }
                decimal before_price = card_Item.now_balance.Value;
                User u_mod = _tool.di_db.Get_rk_List<User>("select top 1 * from [user] where Id=@Id", new { Id = _tool.di_user.RK_USER.Id }).FirstOrDefault();
                if (u_mod == null)
                {
                    result.code = 1;
                    result.msg = "小朋友,你是否有许多问号";
                    return result;
                }
                string update_sql = _tool.di_db.UpdateBySqlstr<rk_card>(new string[] { "now_balance" }, new string[] { "card_id=@card_id" });
                card_Item.now_balance += recharge_money.Value;
                rk_card_record org_card_list = new rk_card_record()
                {
                    addtime = DateTime.Now,
                    card_id = card_Item.card_id,
                    card_no = card_Item.card_no,
                    card_record_id = _tool.di_getid.IGet_SnowFlake_Id,
                    in_price = recharge_money.Value,
                    out_price = 0,
                    operation_remark = "后台充值",
                    pay_details = $"后台充值{recharge_money}元",
                    before_price = before_price,
                    order_no = "recharge_" + _tool.di_getid.IGet_SnowFlake_Id,
                    operation_subject = u_mod.Name,
                    operation_subject_key = u_mod.Id,
                    record_type = record_type.充值,
                    rk_baseuserid = _tool.di_user.RK_USER.BaseUserId,
                    is_mch = false
                };
                string error = "";
                int tran_rows = _tool.di_db.StartRKTran((conn, tran) =>
                {
                    int rows = 0;
                    rows += conn.Execute(update_sql, card_Item, tran);
                    rows += conn.Execute(_tool.di_db.AddBySqlStr<rk_card_record>(), org_card_list, tran);
                    return rows;
                }, ref error);
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "充值成功";
                    result.data = tran_rows;
                }
                else
                {
                    result.code = 1;
                    result.msg = "充值失败";
                    result.data = tran_rows;
                }  
                return result;
            });
        }
        /// <summary>
        /// 保存卡信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel edit_card(edit_card_Params Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.card_id))
                {
                    result.code = 1;
                    result.msg = "卡ID不能为空";
                    return result;
                }
                if (!Params.expiration_time.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须设置有效截至日期";
                    return result;
                }
                rk_card card = _tool.di_db.Get_rk_List<rk_card>("select top 1 * from rk_card  where card_id=@card_id", new { Params.card_id }).FirstOrDefault();
                if (card == null)
                {
                    result.code = 1;
                    result.msg = "卡不存在";
                    return result;
                }
                if (card.rk_baseuserid != _tool.di_user.RK_USER.BaseUserId)
                {
                    result.code = 1;
                    result.msg = "卡不属于您";
                    return result;
                }
                int update_rows = _tool.di_db.do_rk_Execute("update rk_card set card_alias=@card_alias,expiration_time=@expiration_time,card_state=@card_state,remark_a=@remark_a,remark_b=@remark_b where card_id=@card_id", Params);
                if (update_rows > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败";
                }
                return result;
            });
        } 
        /// <summary>
        /// 批量禁用/启用
        /// </summary>
        /// <returns></returns>
        public ResultObjModel batch_change_state(batch_change_params Parmas,bool is_crm = false)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (Parmas.card_ids == null || !Parmas.card_ids.Any())
                {
                    result.code = 1;
                    result.msg = "请选择卡";
                    return result;
                }
                if (!Parmas.card_state.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须指定操作";
                    return result;
                }
                if (!new card_state[] { card_state.已激活, card_state.已禁用 }.Contains(Parmas.card_state.Value))
                {
                    result.code = 1;
                    result.msg = "修改卡状态失败:非法的操作状态";
                    return result;
                }
                //开始修改对应卡状态，修改卡应该为当前指定用户的  卡ID的  状态不为已过期的
                string update_sql = "update rk_card set card_state=@card_state where card_id in @card_ids and card_state not in @no_update_state";
                if (!is_crm)
                {
                    update_sql += "  and rk_baseuserid=@rk_baseuserid ";
                }
                int ipdate_set = _tool.di_db.do_rk_Execute(update_sql, new
                {
                    Parmas.card_state,
                    Parmas.card_ids,
                    rk_baseuserid = _tool.di_user.RK_USER.BaseUserId,
                    no_update_state = new card_state[] { card_state.已过期, card_state.未激活 }
                });
                if (ipdate_set > 0)
                {
                    result.code = 0;
                    result.msg = "批量修改成功";
                }
                else {
                    result.code = 1;
                    result.msg = "批量修改失败";
                }
                return result;
            }); 
        }
         
        /// <summary>
        /// 卡消费列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<card_record_Item> card_record_pagelist(card_record_search query)
        {

            return CoreStartDo.ResultAction<ResultListModel<card_record_Item>>(result =>
            {
                string sql = "select a.*,b.remark_a,b.remark_b from rk_card_record a left join rk_card b on a.card_id=b.card_id";
                string where = " where 1=1 and a.rk_baseuserid=@rk_baseuserid";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.rk_baseuserid = _tool.di_user.RK_USER.BaseUserId;
                if (!string.IsNullOrWhiteSpace(query.order_no))
                {
                    where += " and a.order_no=@order_no";
                    query_dy.order_no = query.order_no;
                } 
                if (!string.IsNullOrWhiteSpace(query.card_no))
                {
                    where += " and a.card_no=@card_no";
                    query_dy.card_no = query.card_no;
                }
                if (!string.IsNullOrWhiteSpace(query.operation_subject))
                {
                    where += " and a.operation_subject like @operation_subject";
                    query_dy.operation_subject = $"%{ query.operation_subject}%";
                } 
                if (query.record_type.HasValue)
                {
                    where += " and a.record_type=@record_type";
                    query_dy.record_type = query.record_type.Value;
                } 
                if (!string.IsNullOrWhiteSpace(query.start_time))
                {
                    where += " and a.addtime>=@start_time";
                    query_dy.start_time = query.start_time;
                }
                if (!string.IsNullOrWhiteSpace(query.end_time))
                {
                    where += " and a.addtime<=@end_time";
                    query_dy.end_time = query.end_time;
                }
                if (!string.IsNullOrWhiteSpace(query.remark_a))
                {
                    where += " and b.remark_a like @remark_a";
                    query_dy.remark_a = $"%{ query.remark_a}%";
                }
                ResultListModel<card_record_Item> result_list = _tool.di_db.GetRKPageList<card_record_Item>(sql, where, "a.addtime", query_dy, query.IsPage, query.page, query.pagesize); 
                return result_list;
            });
        }

        /// <summary>
        /// 导出卡消费信息
        /// </summary>
        public void rk_cardrecord_down_for_shop(card_record_search query)
        {
            query.IsPage = false;
            var listresult = card_record_pagelist(query);
            string title = $"{DateTime.Now.ToString("yyyy-MM-dd")}_卡记录信息.xlsx";
            _excelservice.ExcelExportService(title, listresult.rows, dosomething: fs =>
            {
                _context.HttpContext.Response.ContentType = "application/octet-stream;charset=UTF-8";
                _context.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(title, System.Text.Encoding.UTF8));
                int bufferSize = Convert.ToInt32(fs.Length);
                byte[] buffer;
                buffer = new byte[bufferSize];
                int currentRead = fs.Read(buffer, 0, bufferSize);
                _context.HttpContext.Response.Body.Write(buffer, 0, currentRead);
                _context.HttpContext.Response.Body.Flush();
            });
        }
        #endregion
         
        #region 获取卡信息
        /// <summary>
        /// 获取卡信息
        /// </summary>
        /// <param name="baseuserid"></param>
        /// <param name="card_no"></param>
        /// <returns></returns>
        public ResultObjModel get_card(string baseuserid,string card_no) {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(baseuserid))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(card_no))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参.";
                    return result;
                }
                var card = _tool.di_db.Get_rk_List<rk_card>("select top 1 * from rk_card where card_id=@card_id", new { card_id = $"{baseuserid}-{card_no}" }).FirstOrDefault();
                if (card == null)
                {
                    result.code = 1;
                    result.msg = "卡不存在.";
                    return result;
                }
                if (card.card_state != card_state.已激活)
                {
                    result.code = 1;
                    result.msg = $"当前卡状态{card.card_state.ToString()}";
                    return result;
                }
                if (card.expiration_time <= DateTime.Now)
                {
                    result.code = 1;
                    result.msg = $"当前卡已过期";
                    return result;
                }
                result.code = 0;
                result.msg = "success";
                result.data = new
                {
                    card.card_no,
                    card.remark_a,
                    card.remark_b,
                    card.now_balance
                };
                return result;
            });
        }
        #endregion
    }
}
